package com.example.myprojectoffeixue;
import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;
import com.activity.WifiConfigActivity;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshScrollView;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.nostra13.universalimageloader.cache.disc.naming.Md5FileNameGenerator;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.QueueProcessingType;
import com.test.demo.DeviceListViewActivity;
import com.test.demo.SmartLinkQuickWifiConfigActivity;
import org.apache.http.entity.StringEntity;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

//命名的失误，本fragment是我的设备的界面
public class Kaiguanfg extends Fragment {
    private MyApplication m;
    PullToRefreshScrollView pr;
    private GridView gd;
    ImageView iv;
    ImageView iv_loding;
    SimpleAdapter imageItems;
    TextView reconnect;
    View mimage;
    private List<ImageView> views = new ArrayList<ImageView>();
    private List<ADInfo> infos = new ArrayList<ADInfo>();
    private CycleViewPager cycleViewPager;
    private String[] imageUrls = {"http://a1.qpic.cn/psb?/V133USxU1h2wwM/ujAfnDj7mUsO34Tj4SRqpUA8OBhfKokemRKbxNlXl*8!/b/dG4BAAAAAAAA&bo=rwRYAgAAAAADB9M!&rf=viewer_4",
                                   "http://a1.qpic.cn/psb?/V133USxU1h2wwM/GSVTfXmh0dxOvoO2wA*fEO4shYTq*IktH8yVzpvcFAM!/b/dG4BAAAAAAAA&bo=rwRYAgAAAAADB9M!&rf=viewer_4",
                                   "http://a1.qpic.cn/psb?/V133USxU1h2wwM/MPzKNNPMVBNGV0ZSp7B*stPD6er2OzeqGaTyJm1RxTk!/b/dG4BAAAAAAAA&bo=rwRYAgAAAAADB9M!&rf=viewer_4",
                                  };


    ArrayList<HashMap<String, Object>> lstItems = new ArrayList<HashMap<String, Object>>();
    Handler hand = new Handler() {
        public void handleMessage(Message msg) {
            if (msg.what == 30) {
                if (getActivity() != null) {
                    dialog1.dismiss();
                    HttpConnection.showToast(getActivity(),"连接失败，正在重连");
                    iv_loding.setImageResource(R.drawable.fail_loading);
                    iv_loding.setVisibility(View.VISIBLE);
                    gd.setVisibility(View.GONE);
                    reconnect.setVisibility(View.VISIBLE);
                    mimage.setVisibility(View.GONE);
                }
            }else if (msg.what == 10 && getActivity() != null) {
                //正常显示
                if (dialog1.isShowing()) {
                    dialog1.dismiss();
                }
                if (reconnect.isShown()) {
                    mimage.setVisibility(View.VISIBLE);
                    iv_loding.setVisibility(View.GONE);
                    reconnect.setVisibility(View.GONE);
                    gd.setVisibility(View.VISIBLE);
                }
                setadapter();
            }
        };
    };

    private Dialog dialog1;
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View r = inflater.inflate(R.layout.kaiguanfg, container, false);// 关联布局文件
        configImageLoader();
        initialize();
        mimage=r.findViewById(R.id.fragment_cycle_viewpager_content);
        m = (MyApplication) getActivity().getApplication();
        m.hand = hand;
        reconnect = (TextView) r.findViewById(R.id.tv_default);
        LinearLayout Mywangguan = (LinearLayout) r.findViewById(R.id.iv_mykaiguan);
        gd = (GridView) r.findViewById(R.id.gridview);
        iv_loding = (ImageView) r.findViewById(R.id.iv_loding);
        TextView voice_kaiguan= (TextView) r.findViewById(R.id.voice_kaiguan);
        voice_kaiguan.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                MainActivity ma= (MainActivity) getActivity();
                ma.clickMethod();
            }
        });
        m = (MyApplication) getActivity().getApplication();
        iv = (ImageView) r.findViewById(R.id.iv_kaiguanfg1);

        iv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                    final Dialog dialog = new Dialog(getActivity(), R.style.dialog);
                    dialog.setContentView(R.layout.select_dialog);
                if(m.flag3){
                    dialog.show();}else{
                    ToastUtils.showToast(getActivity(),"与后台连接断开，正在重连");
                }
                    dialog.setCanceledOnTouchOutside(true);
                    TextView tv_gateway = (TextView) dialog.findViewById(R.id.gate_dialog);
                    TextView tv_shebei = (TextView) dialog.findViewById(R.id.shebei_dialog);
                    TextView tv_smart = (TextView) dialog.findViewById(R.id.sm_dialog);
                    TextView tv_addhouse= (TextView) dialog.findViewById(R.id.addhouse);
                    tv_smart.setOnClickListener(new OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            Intent it = new Intent(getActivity(), WifiConfigActivity.class);
                            dialog.dismiss();
                            startActivity(it);
                        }
                    });

                    tv_gateway.setOnClickListener(new OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            Intent it = new Intent(getActivity(), SetYindaoActivity.class);
                            dialog.dismiss();
                            startActivity(it);
                        }
                    });
                    tv_shebei.setOnClickListener(new OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            Intent it = new Intent(getActivity(), SelectActivity.class);
                            dialog.dismiss();
                            startActivity(it);
                        }
                    });

                    tv_addhouse.setOnClickListener(new OnClickListener() {
                        @Override
                        public void onClick(View v) {

                            Intent it=new Intent(getActivity(),HouseActivity.class);
                            dialog.dismiss();
                            startActivity(it);
                        }
                    });


            }

        });


        gd.setOnItemClickListener(new OnItemClickListener() {

            private Intent it;

            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                it = new Intent(getActivity(), MyKgActivity.class);
                // Intent it1=new Intent(getActivity(),AddCameraActivity.class);
                TextView tv = (TextView) view.findViewById(R.id.itemText);
                if ("开关".equals(tv.getText().toString())) {
                    it = new Intent(getActivity(), Switch.class);
                    startActivity(it);
                } else if ("门锁".equals(tv.getText().toString())) {
                    it.putExtra("flag", 1);
                    startActivity(it);

                } else if ("红外人体感应".equals(tv.getText().toString())) {
                    it.putExtra("flag", 2);
                    startActivity(it);

                } else if ("窗帘".equals(tv.getText().toString())) {
                    it.putExtra("flag", 3);
                    startActivity(it);
                } else if ("门磁".equals(tv.getText().toString())) {


                    it.putExtra("flag", 4);
                    startActivity(it);

                } else if ("取电开关".equals(tv.getText().toString())) {

                    it.putExtra("flag", 5);
                    startActivity(it);


                } else if ("红外转发器".equals(tv.getText().toString())) {

                    it.putExtra("flag", 6);
                    startActivity(it);

                } else if ("中央空调".equals(tv.getText().toString())) {

                    Intent it5 = new Intent(getActivity(), KtGroupActivity.class);
                    startActivity(it5);
                } else if ("智能插座".equals(tv.getText().toString())) {
                    it.putExtra("flag", 8);
                    startActivity(it);
                } else if("摄像头".equals(tv.getText().toString())){
                    it=new Intent(getActivity(),DeviceListViewActivity.class);
                    startActivity(it);
                }
            }
        });
pr= (PullToRefreshScrollView) r.findViewById(R.id.scrollview);
pr.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ScrollView>() {
    @Override
    public void onPullDownToRefresh(PullToRefreshBase<ScrollView> refreshView) {
        m.GetDeviceList();
        pr.onRefreshComplete();
    }

    @Override
    public void onPullUpToRefresh(PullToRefreshBase<ScrollView> refreshView) {

       // ToastUtils.showToast(getActivity(),"hhhhhhhhhhhhhhhhh");
    }
});
        return r;
    }


   @Override
    public void onStart() {
       Log.d("哈哈哈","我来了");
       m = (MyApplication) getActivity().getApplication();
       m.hand = hand;
       dialog1 = new Dialog(getActivity(), R.style.myDialogTheme);
       dialog1.setContentView(R.layout.progressdialog);
       if(!MyApplication.localflag) {
           if (m.flag6) {
               dialog1.show();
               m.connect();
               Log.d("heheh", "123");
               m.flag6 = false;
               new Thread() {
                   @Override
                   public void run() {
                       for (int i = 0; i < 2; i++) {
                           if (m.flag3) {
                               return;
                           } else {
                               try {
                                   sleep(1000);
                               } catch (InterruptedException e) {
                                   e.printStackTrace();
                               }
                           }

                       }
                       if (dialog1.isShowing()) {
                           hand.sendEmptyMessage(30);
                       }
                   }
               }.start();
           } else {
               if (m.c.getReadyState() == 1) {
                   m.GetDeviceList();
                   setadapter();
               }
           }
       }else{
           m.Get();
       }
        super.onStart();
    }


    public void setadapter() {
        int[] mainInterfaceImageIDs = new int[10];
        String[] mainInterfaceStr = new String[10];
        lstItems.clear();
        if (m.lsb.size() != 0) {
            mainInterfaceImageIDs[0] = R.drawable.kai;
            mainInterfaceStr[0] = "开关";
        }
        if (m.lsb1.size() != 0) {
            mainInterfaceImageIDs[1] = R.drawable.ms;
            mainInterfaceStr[1] = "门锁";
        }
        if (m.lsb2.size() != 0) {
            mainInterfaceImageIDs[2] = R.drawable.hw2;
            mainInterfaceStr[2] = "红外人体感应";
        }
        if (m.lsb3.size() != 0) {
            mainInterfaceImageIDs[3] = R.drawable.cl2;
            mainInterfaceStr[3] = "窗帘";
        }
        if (m.lsb4.size() != 0) {
            mainInterfaceImageIDs[4] = R.drawable.mc;
            mainInterfaceStr[4] = "门磁";
        }
        if (m.lsb5.size() != 0) {
            mainInterfaceImageIDs[5] = R.drawable.qudiana;
            mainInterfaceStr[5] = "取电开关";

        }
        if (m.lsb6.size() != 0) {
            mainInterfaceImageIDs[6] = R.drawable.hwzfq;
            mainInterfaceStr[6] = "红外转发器";
        }
        if (m.lsb7.size() != 0) {
            mainInterfaceImageIDs[7] = R.drawable.zykt;
            mainInterfaceStr[7] = "中央空调";
        }
        if (m.lsb8.size() != 0) {
            Log.d("插座","cz");
            mainInterfaceImageIDs[8] = R.drawable.chazuokai;
            mainInterfaceStr[8] = "智能插座";
        }
        mainInterfaceImageIDs[9]=R.drawable.sxt;
        mainInterfaceStr[9]="摄像头";
/*
                mainInterfaceImageIDs[9]=R.drawable.jka;
				mainInterfaceStr[9]="摄像头";*/
        for (int j = 0; j < mainInterfaceImageIDs.length; j++) {
            if (mainInterfaceImageIDs[j] != 0) {
                HashMap<String, Object> map = new HashMap<String, Object>();
                map.put("itemsImage", mainInterfaceImageIDs[j]);
                map.put("itemsText", mainInterfaceStr[j]);
                lstItems.add(map);
            }
        }
        if (lstItems.size() == 0) {
            gd.setVisibility(View.GONE);
            iv_loding.setVisibility(View.VISIBLE);
            iv_loding.setImageResource(R.drawable.frist_loading);
            reconnect.setVisibility(View.VISIBLE);
            if(m.m_gateway.size()==0){
                reconnect.setText("快去添加网关吧！");
            }else{
                int h=0;
                for(int j=0;j<m.m_gateway.size();j++){
                    if(m.m_gateway.get(j).isOnline!=null&&!m.m_gateway.get(j).isOnline){
                        h=1;
                    }
                }
                if(h==1){
                     reconnect.setText("存在网关掉线，请检查网络");}else{
                    reconnect.setText("快去添加设备吧!");
                }
            }
            reconnect.setVisibility(View.VISIBLE);
        } else {
            reconnect.setVisibility(View.GONE);
            iv_loding.setVisibility(View.GONE);
            gd.setVisibility(View.VISIBLE);
            if (imageItems == null) {
                imageItems = new SimpleAdapter(getActivity(), lstItems, R.layout.item_grid,
                        new String[]{"itemsImage", "itemsText"}, new int[]{R.id.itemImage, R.id.itemText});
                gd.setAdapter(imageItems);
            } else {
                imageItems.notifyDataSetChanged();
            }
            gd.setSelector(new ColorDrawable(Color.TRANSPARENT));

        }

    }


    @SuppressLint("NewApi")
    private void initialize() {

        cycleViewPager = (CycleViewPager) getActivity().getFragmentManager().findFragmentById(R.id.fragment_cycle_viewpager_content);

        for(int i = 0; i < imageUrls.length; i ++){
            ADInfo info = new ADInfo();
            info.setUrl(imageUrls[i]);
            info.setContent("图片-->" + i );
            infos.add(info);
        }

        // 将最后一个ImageView添加进来
        views.add(ViewFactory.getImageView(getActivity(), infos.get(infos.size() - 1).getUrl()));
        for (int i = 0; i < infos.size(); i++) {
            views.add(ViewFactory.getImageView(getActivity(), infos.get(i).getUrl()));
        }
        // 将第一个ImageView添加进来
        views.add(ViewFactory.getImageView(getActivity(), infos.get(0).getUrl()));

        // 设置循环，在调用setData方法前调用
        cycleViewPager.setCycle(true);
        // 在加载数据前设置是否循环
        cycleViewPager.setData(views, infos, mAdCycleViewListener);
        //设置轮播
        cycleViewPager.setWheel(true);

        // 设置轮播时间，默认5000ms
        cycleViewPager.setTime(5000);
        //设置圆点指示图标组居中显示，默认靠右
        cycleViewPager.setIndicatorCenter();
    }

    private CycleViewPager.ImageCycleViewListener mAdCycleViewListener = new CycleViewPager.ImageCycleViewListener() {

        @Override
        public void onImageClick(ADInfo info, int position, View imageView) {
            if (cycleViewPager.isCycle()) {
                position = position - 1;
                Toast.makeText(getActivity(), "position-->" + info.getContent(), Toast.LENGTH_SHORT).show();
            }

        }

    };

    /**
     * 配置ImageLoder
     */
    private void configImageLoader() {
        // 初始化ImageLoader
        @SuppressWarnings("deprecation")
        DisplayImageOptions options = new DisplayImageOptions.Builder().showStubImage(R.drawable.icon_stub) // 设置图片下载期间显示的图片
                .showImageForEmptyUri(R.drawable.icon_empty) // 设置图片Uri为空或是错误的时候显示的图片
                .showImageOnFail(R.drawable.icon_error) // 设置图片加载或解码过程中发生错误显示的图片
                .cacheInMemory(true) // 设置下载的图片是否缓存在内存中
                .cacheOnDisc(true) // 设置下载的图片是否缓存在SD卡中
                // .displayer(new RoundedBitmapDisplayer(20)) // 设置成圆角图片
                .build(); // 创建配置过得DisplayImageOption对象

        ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(getActivity().getApplicationContext()).defaultDisplayImageOptions(options)
                .threadPriority(Thread.NORM_PRIORITY - 2).denyCacheImageMultipleSizesInMemory()
                .discCacheFileNameGenerator(new Md5FileNameGenerator()).tasksProcessingOrder(QueueProcessingType.LIFO).build();
        ImageLoader.getInstance().init(config);
    }
}